package com.bootdo.common.utils;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class UploadUtils {

    /**
     * 将base64文件保存在指定目录
     * 并返回对应的文件名称
     * @return
     */
    public static String upload(String url, String fileName, String type, String base64){
        String typeName = null;
        Long desFileSize = 30L;
        if ("1".equals(type)){
            typeName = "payment/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
            //二维码
            url += "payment/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
        } else if ("2".equals(type)){
            typeName = "receipt/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
            //回单凭证
            url += "receipt/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
            desFileSize = 500L;
        } else if ("3".equals(type)){
            //充值
            typeName = "recharge/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
            url += "recharge/" + DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
            desFileSize = 500L;
        }

        base64 = base64.trim();
        byte[] bytes = Base64.decodeBase64(base64);
        bytes = PicUtils.compressPicForScale(bytes, desFileSize, fileName.substring(0, fileName.lastIndexOf(".")));
        File dir = new File(url);
        if (!dir.exists()){
            dir.mkdirs();
        }
        FileOutputStream outputStream = null;
        String path = url + "/" + fileName;
        File file = new File(path);
        try {
            file.createNewFile();//创建文件
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null){
                outputStream = null;
            }
        }
        return path.replaceAll(url, typeName);
    }

}
